package com.ruoyi.framework.security.handle

import com.alibaba.fastjson2.JSON
import com.ruoyi.common.constant.HttpStatus
import com.ruoyi.common.core.domain.AjaxResult.Companion.error
import com.ruoyi.common.utils.MyStringUtils
import com.ruoyi.common.utils.ServletUtils.renderString
import org.springframework.security.core.AuthenticationException
import org.springframework.security.web.AuthenticationEntryPoint
import org.springframework.stereotype.Component
import java.io.IOException
import java.io.Serializable
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 认证失败处理类 返回未授权
 *
 * @author ruoyi
 */
@Component
class AuthenticationEntryPointImpl : AuthenticationEntryPoint, Serializable {
    @Throws(IOException::class)
    override fun commence(request: HttpServletRequest, response: HttpServletResponse, e: AuthenticationException) {
        val code = HttpStatus.UNAUTHORIZED
        val msg = MyStringUtils.format("请求访问：{}，认证失败，无法访问系统资源", request.requestURI)
        renderString(response, JSON.toJSONString(error(code, msg)))
    }

    companion object {
        private const val serialVersionUID = -8970718410437077606L
    }
}
